package com.hphs.advice;

import cn.hutool.json.JSONUtil;
import com.hphs.dto.ResponseDTO;
import com.hphs.exception.BizException;
import com.hphs.info.PageInfo;
import com.hphs.threadlocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

//接口增强类
@RestControllerAdvice  // 对controller接口的增强
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    //支持哪些方法  默认是不支持任何方法的
    @Override
    public boolean supports(
            MethodParameter methodParameter,
            Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }
    @ExceptionHandler
    public Object processException(Exception exception){
        exception.printStackTrace();
        BizException bizException= (BizException) exception;
        if(exception instanceof BizException){
            return ResponseDTO.error(bizException.getCode(),exception.getMessage());
        }
        return ResponseDTO.error(88,exception.getMessage());
    }

    // 增强的逻辑
    @Override
    public Object beforeBodyWrite(
            Object bady,
            MethodParameter methodParameter,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {

        if(bady instanceof  ResponseDTO){
            return bady;
        }
        ResponseDTO dto=ResponseDTO.success(bady);
        //使用ThreadLocal 进行标签的粘贴
        PageInfo pageInfo= LocalPageInfoUtil.get();
        if(pageInfo !=null){
            HashMap<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",bady);
            dto=ResponseDTO.success(map);
            LocalPageInfoUtil.remove();
        }
        if(aClass == StringHttpMessageConverter.class){
            //给成json类型的数据
            return JSONUtil.toJsonStr(dto);
        }


        return dto;
    }
}
